import md5 from "crypto-js/md5.js";
const removeNullPro = (obj) => {
  let newObj = {};
  if (typeof obj === 'string') {
    obj = JSON.parse(obj)
  }
  if (obj instanceof Array) {
    newObj = []
  }
  if (obj instanceof Object) {
    Object.keys(obj).forEach(function (k) {
      var value = obj[k];
      if (obj.hasOwnProperty(k) && value !== '' && value !== null && value !== undefined && value !== 'null') {
        if (value instanceof Array || value instanceof Object) {
          newObj[k] = JSON.stringify(value);
        } else {
          newObj[k] = value;
        }
      }
    });
  }
  return newObj;
}

const dwSign = (request) => {
  let millisecond = new Date().getTime();
  request.headers.Timestamp = millisecond;
  let _method = request.method.toLocaleString().toLocaleUpperCase();
  if (_method === 'POST') {
    let _sig = [];
    let Sign = '';
    let sortData = removeNullPro(request.data);
    Object.keys(sortData).forEach(v => {
      _sig.push(`${v}=${sortData[v]}`)
    });
    // console.log(_sig)
    if ( _sig.length > 0 ) {
      Sign = millisecond + '&' + _sig.sort().join('&') + '&012AsHa6%)a12ssc2022_';
    }else {
      Sign = millisecond + _sig.sort().join('&') + '&012AsHa6%)a12ssc2022_';
    }
    request.headers.Sign = md5(Sign).toString()
  } else if (_method === 'GET') {
    if (request.params) {
      let _sig = [];
      let _data = removeNullPro(request.params);
      Object.keys(_data).forEach(v => {
        _sig.push(`${v}=${_data[v]}`)
      });
      let Sign = millisecond + '&' + _sig.sort().join('&') + '&012AsHa6%)a12ssc2022_'
      request.headers.Sign = md5(Sign).toString()
    } else {
      let list = request.url.split('?')
      if (list.length > 1) {
        let Sign = millisecond + '&' + list[list.length - 1] + '&012AsHa6%)a12ssc2022_'
        request.headers.Sign = md5(Sign).toString()
      } else {
        let Sign = millisecond + '&012AsHa6%)a12ssc2022_'
        request.headers.Sign = md5(Sign).toString()
      }
    }
  }
  return request;
}

export default dwSign;